import cv2
import numpy as np
from matplotlib import pyplot as plt

# 读取图像
image = cv2.imread(r'C:\Users\86157\Desktop\course2024-2\pattern recognition\c.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 使用Sobel算子检测边缘
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5)
sobel = cv2.magnitude(sobelx, sobely)

# 将Sobel结果转换为8位无符号整数
sobel_uint8 = np.uint8(np.absolute(sobel))

# 显示原图和边缘图
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1), plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)), plt.title('Original Image')
plt.subplot(1, 2, 2), plt.imshow(sobel_uint8, cmap='gray'), plt.title('Edge Image')
plt.show()